package org.com.ashen.service.util;

import java.io.IOException;
import java.io.Writer;

import org.apache.commons.lang3.text.StrBuilder;

public class CodeUtil {

	public static int getStrlength(String str) {
		int strLength = 0;
		String chinese = "[\u0391-\uFFE5]";
		/* 获取字段值的长度，如果含中文字符，则每个中文字符长度为2，否则为1 */
		for (int i = 0; i < str.length(); i++) {
			/* 从字符串中获取一个字符 */
			String temp = str.substring(i, i + 1);
			/* 判断是否为中文字符 */
			if (temp.matches(chinese)) {
				/* 中文字符长度为2 */
				strLength += 2;
			} else {
				/* 其他字符长度为1 */
				strLength += 1;
			}
		}
		return strLength;
	}

	public static String toStr(byte[] bytes) {
		if (bytes == null || bytes.length == 0) {
			return null;
		}
		char[] hexDigits = {'0','1','2','3','4','5','6','7','8','9', 'A','B','C','D','E','F' };

		//4位代表一个16进制，所以长度需要变为原来2倍
		char[] result = new char[bytes.length*2];

		int index = 0;
		for(byte b:bytes)
		{
			//先转换高4位
			result[index++] = hexDigits[(b>>>4)& 0xf];
			result[index++] = hexDigits[b& 0xf];
		}
		return new String(result);
	}


	public static String Decode(String originstr) {
		
		char[] a1 = new char[originstr.length()];
		a1 = originstr.toCharArray();
		StringBuffer sb1 = new StringBuffer();
		for (int i = 0; i < a1.length; i++) {
			if (i%2==0) {
				sb1.append((int)a1[i]-2+",");
			}else {
				sb1.append((int)a1[i]+1+",");
			}

		}
		
		

		//ASCII码转换成汉字
		String s2 = sb1.toString() ;
		String[] s3 = s2.split(",");
		int[] t1 = new int[s3.length];
		for (int i = 0; i < s3.length; i++) {
		t1[i] = Integer.parseInt(s3[i]);
		}

		String laststr = "";
		for (int i = 0; i < t1.length; i++) {
			laststr+=(char)(t1[i]);
		}
		return laststr;
	}
	
	
	public static String Encode(String str) {
		//汉字转换成ASCII码
		char[] a = new char[str.length()];
		a = str.toCharArray();
		StringBuffer sb = new StringBuffer();
		for (int i = 0; i < a.length; i++) {
			if (i%2==0) {
				sb.append((int)a[i]+2+",");
			}else {
				sb.append((int)a[i]-1+",");
			}
		}

		//ASCII码转换成汉字
		String s = sb.toString();
		String[] s1 = s.split(",");
		int[] t = new int[s1.length];
		for (int i = 0; i < s1.length; i++) {
		t[i] = Integer.parseInt(s1[i]);
		}

		String originstr = "";
		for (int i = 0; i < t.length; i++) {
		originstr+=(char)(t[i]);
		}

		return originstr;
	}


}
